﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.Linq;
using MethodWorx.CMS.Content;
using System.Data.Linq;

namespace MethodWorx.CMS.Linq
{
    public class LinqPageRepository : LinqRepository<LinqPage, Page>, IPageRepository
    {
        public LinqPageRepository(DataContext context)
            : base(context)
        {
            //
            //  set this repository to only return deleted items
            this.source = this.source.Where(s => s.Status != ContentStatus.Deleted);
        }

        public Page FindRoot()
        {
            return this.source.Cast<LinqPage>().Where(p => p.ParentId == null).FirstOrDefault();
        }

        protected override void OnUpdate(LinqPage entity)
        {
            entity.Workflows = entity.Workflows;
            entity.PublishedWorkflows = entity.PublishedWorkflows;
            entity.PublishedTemplate = entity.PublishedTemplate;
            entity.PublishedScript = entity.PublishedTemplate;
            entity.Properties = entity.Properties;

            this.PersistPublisedPlaceholders(entity);

            base.OnUpdate(entity);
        }

        private void PersistPublisedPlaceholders(LinqPage entity)
        {
            if(entity.HavePublishedPlaceholdersBeenLoaded)
            {
                var table = this.context.GetTable<LinqPublishedPlaceholder>();
                foreach (var pp in table.Where(c => c.PageId == entity.Id))
                {
                    table.DeleteOnSubmit(pp);
                }

                //
                //  now create soem more
                foreach (var pp in entity.PublishedPlaceholders.Keys)
                {
                    var lpp = new LinqPublishedPlaceholder();
                    lpp.Id = Guid.NewGuid();
                    lpp.Name = pp;
                    lpp.Code = entity.PublishedPlaceholders[pp];
                    lpp.Page = entity;

                    table.InsertOnSubmit(lpp);
                }
            }
        }

        public IEnumerable<Page> FindByTags(string [] tags)
        {
            foreach(string tag in tags)
            {
                if (!string.IsNullOrEmpty(tag))
                {
                    foreach (Page page in this.source)
                    {
                        if(page.Tags.ToLower().Contains(tag.ToLower()))
                            yield return page;
                    }
                }
            }
        }


        public IEnumerable<Page> FindByTemplate(string template)
        {
            return this.source.Cast<LinqPage>().Where(p => p.ProxyTemplate.Name == template);
        }

    }
}
